package database;


import org.htmlparser.NodeFilter;
import org.htmlparser.beans.FilterBean;

import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;

import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public abstract class Parseador {
	static private String url = "http://www.bcentral.cl/index.asp";
	
	public static String parsearUF(Context context)
	{
		NodeList nodelist = Parseador.getDIVTag();
		NodeList list = new NodeList();
    	NodeFilter filter = new TagNameFilter ("TR");

		try {
	    	for (NodeIterator e = nodelist.elements() ; e.hasMoreNodes ();)
					e.nextNode ().collectInto (list, filter);
			} catch (ParserException e1) {
				e1.printStackTrace();
			}

		if (Consulta.consultAllUF(context).getCount() > 0)
		{
			Consulta.editUF(context, "uf", parsearNodo(list.elementAt(0).toHtml().toString()));
			
		}
		else
		{
			Consulta.insertUF(context, "uf", parsearNodo(list.elementAt(0).toHtml().toString()));
		}
		return parsearNodo(list.elementAt(0).toHtml().toString());
		
	}
		
	private static NodeList getDIVTag(){
		
		TagNameFilter filtroDIV = new TagNameFilter ();
	    filtroDIV.setName ("DIV");
	    HasAttributeFilter filter1 = new HasAttributeFilter();
	    filter1.setAttributeName("id");
	    filter1.setAttributeValue("ind-dia");
	      
	    NodeFilter[] array0 = new NodeFilter[1];
	    array0[0] = filter1;
	    
	    FilterBean bean = new FilterBean ();
	    
	    bean.setURL (url);
	    bean.setFilters (array0);
	    	
	    return bean.getNodes();
	}

	private static String parsearNodo(String tagUF)
	{
		int inicio = tagUF.lastIndexOf("<td>") + 4;
		int fin = tagUF.lastIndexOf("</td>");
		
		
		return formatearUF(tagUF.substring(inicio, fin));
	}
	
	private static String formatearUF(String uf)
	{
		String newUF = uf.replace(".", "");
		newUF = newUF.replace(",", ".");
		
		return newUF;
	}
	
	public static boolean verificarConexion(Context ctx) {
		boolean bConectado = false;
		ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] redes = connec.getAllNetworkInfo();
		for (int i = 0; i < 2; i++) {
			if (redes[i].getState() == NetworkInfo.State.CONNECTED) 
			{
				bConectado = true;
			}
		}
		return bConectado;
	}

}
